package com.dys.dao.impl;

import com.dys.dao.IStudentDao;
import com.dys.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @className: com.dys.dao.impl.StudentDaoImpl
 * @description: com.dys.dao.impl
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/10/21 20:56
 */
@Repository
public class StudentDaoImpl implements IStudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Student> findAll() {
        String sql = "select * from student";
        List<Student> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
        return list;
    }

    @Override
    public List<Student> listStudents() {
        String sql = "select * from student";
        List<Student> list = jdbcTemplate.query(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
                Student student = new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setAge(rs.getInt("age"));
                student.setSex(rs.getString("sex"));
                return student;
            }
        });
        return list;
    }

    @Override
    public int addStudent(Student student) {
        String sql = "insert into student(name,age,sex) values(?,?,?)";
        int count = jdbcTemplate.update(sql, student.getName(), student.getAge(), student.getSex());
        return count;
    }

    @Override
    public int updateStudent(Student student) {
        String sql = "update student set name=?,age=?,sex=? where id=?";
        int count = jdbcTemplate.update(sql, student.getName(), student.getAge(), student.getSex(), student.getId());
        return count;
    }

    @Override
    public int deleteStudentById(int id) {
        String sql = "delete from student where id = ?";
        int count = jdbcTemplate.update(sql, id);
        return count;
    }
}
